package com.acegear.horizon.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.mashape.unirest.http.ObjectMapper;
import com.mashape.unirest.http.Unirest;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

import javax.annotation.PostConstruct;

import javaslang.jackson.datatype.JavaslangModule;
import redis.clients.jedis.Jedis;

/**
 * Created by mercury on 2016/12/11.
 */
@Configuration
public class UtilConfig {

    @Value("${horizon.cache.redis.url}")
    private String redisUrl;

    @Value("${horizon.cache.redis.auth}")
    private String redisAuth;

    @Bean
    public Jedis getJedis() {
        Jedis jedis = new Jedis(redisUrl);
        if (redisAuth != null && !redisAuth.isEmpty()) {
            jedis.auth(redisAuth);
        }
        return jedis;
    }

    @Bean
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        return new PoolingHttpClientConnectionManager();
    }

    @Bean
    public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper() {
        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
        mapper.registerModule(new JavaslangModule());
        return mapper;
    }

    @PostConstruct
    public void initUnirest() {
        Unirest.setObjectMapper(new ObjectMapper() {
            private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
                    = new com.fasterxml.jackson.databind.ObjectMapper();

            public <T> T readValue(String value, Class<T> valueType) {
                try {
                    return jacksonObjectMapper.readValue(value, valueType);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            public String writeValue(Object value) {
                try {
                    return jacksonObjectMapper.writeValueAsString(value);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
